#ifndef _EVENT_LOOP_H_
#define _EVENT_LOOP_H_

#include <stdint.h>
#include <vector>
#include <mutex>
#include <condition_variable>
#include "socket.h"
#include "poller.h"

namespace as
{

namespace snet
{


struct event_base
{
	enum EventType
	{
		EV_NONE = 0,
		EV_ACCEPT = 1,
		EV_READ = 2,
		EV_WRITE = 3,
		EV_ACCEPT_UPDATE = 99,
	};

	uint8_t m_event_type = 0;
	void *m_handle_ptr = nullptr;
	socket_fd m_fd = 0;
};

typedef std::vector<event_base> EventVec;
class EventLoop : public PollerInstance
{
public:
	enum
	{
		WORK_STATE_NONE,
		WORK_STATE_WORKING,
		WORK_STATE_READY_STOP,
		WORK_STATE_STOP,
	};

	EventLoop();
	void start(int workthreadNum = 1);
	void stop();
	void run();
	void work_run();

	void add_event(const event_base &ev);
	void handle_read(socket_fd fd);
	void handle_write(socket_fd fd);

	virtual void on_poll(void *key, void *ev);
private:
	std::atomic_int8_t m_state = 0;

	EventVec m_eventList;

	std::mutex m_lock;
	std::condition_variable m_cv;
	bool m_hasEvent = false;
	std::vector<std::thread> m_workThread;

	std::unique_ptr<Poller> m_workPoller;
};
}
}

#endif